package com.keymozy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keymozy.mapper.DeptMapper;
import com.keymozy.mapper.StaffMapper;
import com.keymozy.pojo.Dept;
import com.keymozy.pojo.Staff;
import com.keymozy.pojo.dto.DtoDept;
import com.keymozy.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class IDeptService extends ServiceImpl<DeptMapper, Dept> implements DeptService {
    @Autowired
    private StaffMapper staffMapper;
    @Override
    public Map<String, Object> depts(Integer current, Integer pageSize, Dept dept) {
        LambdaQueryWrapper<Dept> deptLambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(dept!=null){
            deptLambdaQueryWrapper.eq(dept.getId()!=null,Dept::getId,dept.getId());
            deptLambdaQueryWrapper.eq(dept.getDname()!=null,Dept::getDname,dept.getDname());
            deptLambdaQueryWrapper.eq(dept.getSid()!=null,Dept::getSid,dept.getSid());
        }
        Page<Dept> page = new Page<>(current, pageSize);
        Page<Dept> deptPage = baseMapper.selectPage(page, deptLambdaQueryWrapper);
        List<Dept> records = deptPage.getRecords();
        for (Dept record : records) {
            Integer sid = record.getSid();
            String uname = staffMapper.selectById(sid).getUname();
            record.setName(uname);
        }
        List<Staff> staff = staffMapper.selectList(new LambdaQueryWrapper<Staff>()
                .select(Staff::getId, Staff::getUname).last("limit 0,10"));
        Map<String, Object> map = new HashMap<>();
        map.put("total",deptPage.getTotal());
        map.put("records",records);
        map.put("recordSize",records.size());
        map.put("size",deptPage.getSize());
        map.put("current",deptPage.getCurrent());
        map.put("staffs",staff);
        return map;
    }

    @Override
    public List<DtoDept> echartDept() {
        ArrayList<DtoDept> dtoDepts = new ArrayList<>();
        List<Dept> depts = baseMapper.selectList(null);
        for (Dept dept : depts) {
            Integer count = staffMapper.selectCount(new LambdaQueryWrapper<Staff>().eq(Staff::getDid, dept.getId()));
            DtoDept dtoDept = new DtoDept();
            dtoDept.setName(dept.getDname());
            dtoDept.setValue(count);
            dtoDepts.add(dtoDept);
        }
        return dtoDepts;
    }
}
